<template>
  <div class="loadHomeWork">
    <div class="loadHomeWorkIneer">
      <div class="loadTop">船用通讯录</div>
      <div class="loadAndSearch">
        <div class="loadExcel">
          <div class="button" type="success" @click="uploadFile()">导入</div>
          <div class="button" type="success" @click="getExcelFile()">导出</div>
          <div class="button" type="success" @click="addOne()">新增</div>
          <div class="multiButton" type="success" @click="deleteMulti()">
            删除
          </div>
        </div>
        <!-- <div class="search1">
          <el-config-provider :locale="locale">
            <el-date-picker
              v-model="value2"
              style="height: 24px; width: 240px"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="x"
              :default-value="[new Date(), new Date()]"
            />
          </el-config-provider>
          <div class="searchButton" @click="getRenderList()">搜索</div>
        </div> -->
      </div>
      <div class="table" :style="{ width: tableWidth }">
        <el-table
          empty-text="暂无数据"
          :header-cell-style="{
            background: '#FAFAFA',
            color: '#777676 !important',
            fontWeight: '800',
          }"
          :data="tableData"
          @row-dblclick="handleRowDblclick"
          :row-style="{ height: 30 + 'px', lineHeight: '16px' }"
          :cell-style="{ padding: 0 + 'px' }"
          border
          stripe
          style="width: 100%; height: auto"
          max-height="65vh"
          @selection-change="selecttableFunction"
        >
          <el-table-column type="selection" width="35" align="center" />

          <el-table-column
            type="index"
            align="center"
            label="序号"
            min-width="55"
            :index="indexNumber"
          >
          </el-table-column>

          <el-table-column
            align="center"
            label="名称"
            min-width="200"
            prop="name"
          >
          </el-table-column>
          <el-table-column
            align="center"
            label="联系电话"
            min-width="100"
            prop="phoneNumber"
          />
          <el-table-column
            align="center"
            label="其他联系方式"
            min-width="100"
            prop="otherContact"
          />
          <el-table-column
            align="center"
            label="备注"
            min-width="100"
            prop="remark"
          />
        </el-table>
        <!-- 内容过多，会出现滚动条 -->
      </div>
      <div class="foot">
        <div class="currentPage">当前第{{ page }}/{{ totalPages }}页</div>
        <div
          class="lastPage"
          :style="{ background: color }"
          @click="clickLastPage()"
        >
          上一页
        </div>
        <div
          class="nextPage"
          :style="{ backgroundColor: color1 }"
          @click="clickNextPage()"
        >
          下一页
        </div>
        <div class="currentNumber">共{{ totalNumber }}条</div>
        <div>跳转至:</div>
        <input
          type="text"
          class="skipPage"
          style="width: 50px !important"
          v-model="shipPageNumer"
        />
        <div class="sureSkip" @click="skipPage">确定</div>
      </div>
    </div>
    <div class="dialog" ref="dialog" :style="{ display: show }">
      <div class="loadHomeWorkIneer">
        <div class="changeTop">
          <div
            class="delete"
            @click="deleteOne(id)"
            v-show="addOrEdit == '编辑'"
          >
            删除
          </div>
          <div class="sure" @click="sureAdd()">确认</div>
          <div class="back" @click="backToIndex()">返回</div>
        </div>
        <div class="dialogText">{{ addOrEdit }}</div>
        <div class="manyInput">
          <div class="iuptInnerContain">
            <div class="inputInner">
              <div class="name">名称:</div>
              <input placeholder="名称" v-model="name" />
            </div>
            <div class="inputInner">
              <div class="name">联系电话:</div>

              <input placeholder="联系电话" v-model="phoneNumber" />
            </div>
            <div class="inputInner">
              <div class="name">其他联系方式:</div>
              <input placeholder="其他联系方式" v-model="otherContact" />
            </div>
            <div class="inputInner">
              <div class="name">备注:</div>
              <input name="" id="" placeholder="备注" v-model="remark" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="dialog2" :style="{ display: uploadfile }">
      <div class="upContain">
        <input
          type="file"
          ref="clearFile"
          class="addfile"
          @change="getFile($event)"
          accept=".xls,.xlsx"
        />
      </div>
      <div class="fileName">
        <div v-show="fileName">文件名:{{ fileName }}</div>
      </div>
      <div class="upFileSrue">
        <button class="buttonUpdata" @click="cancelUp()">取消</button>
        <button class="buttonUpdata buttonUpdata1" @click="submitAddFile()">
          确定
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import EventBus from "@/mitt/eventBus.js";
import rename from "@/mitt/getPath.js";
import service from "@/api/api";
import _ from "lodash";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import axios from "axios";
export default {
  name: "",
  data() {
    return {
      shipPageNumer: 1,
      compare: {},
      multi: [],
      token: "",
      locale: zhCn,
      totalNumber: 0,
      tableData: [],
      showQuit: false,
      menu: "menu1",
      page: 1,
      size: 20,
      show: "none",
      addOrEdit: "新增",
      currentNum: 0,
      name: "",
      phoneNumber: "",
      remark: "",
      otherContact: "",
      tableWidth: null,
      serialNumber: "",
      totalPages: null,
      id: "",
      uploadfile: true,
      data: {
        name: "",
        phoneNumber: "",
        remark: "",
        otherContact: "",
        id: "",
      },

      show1: "none",
      color: "#EBEBEB",
      color1: "#EBEBEB",
      file: null,
      fileName: "",
      sonTable: {},
    };
  },
  props: [],
  components: {},
  computed: {},
  filters: {},

  methods: {
    indexNumber(index) {
      return (this.page - 1) * this.size + index + 1;
    },

    handleRowDblclick(row) {
      this.clickEdit(row.id);
    },

    // 跳转页面
    skipPage() {
      if (this.shipPageNumer <= this.totalPages && this.shipPageNumer > 0) {
        this.page = this.shipPageNumer;
        this.getRenderList();
      } else {
        this.$message({
          type: "warning",
          message: "超出页面数量范围",
        });
      }
    },

    // 批量删除开始========================
    selecttableFunction(row) {
      if (row.length > 0) {
        this.multi = [];
        row.forEach((element) => {
          this.multi.push(element.id);
        });
      } else {
        this.multi = [];
      }
    },
    deleteMulti() {
      // let that = this;
      if (this.multi.length == 0) {
        return this.$message({
          type: "warning",
          message: "请先选中再进行批量删除操作！",
        });
      }
      let data = {
        idList: this.multi + "",
      };

      this.$alert("确定删除选中的信息？", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            service({
              method: "delete",
              url: `/address-book`,
              params: data,
            }).then((r) => {
              if (r.status == "SUCCESS") {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                if (this.currentNum == this.multi.length && this.page > 1) {
                  this.page--;
                }
                this.getRenderList();
              }
            });
          } else {
            this.$message({
              type: "info",
              message: "取消删除",
            });
          }
        },
      });
    },
    //批量删除结束=============================

    // 导入文件================
    uploadFile() {
      this.uploadfile = "block";
    },
    getFile(event) {
      this.file = event.target.files[0];
      this.fileName = this.file.name;
    },

    submitAddFile() {
      if (this.file) {
        let data = {
          file: this.file,
        };
        service({
          method: "post",
          url: "/address-book/upload",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          data: data,
        })
          .then((res) => {
            document.getElementsByClassName("addfile")[0].value = "";
            this.$message({
              message: "上传成功",
              type: "success",
            });
            this.file = "";
            this.fileName = "";
            this.uploadfile = "none";
            this.getRenderList();
          })
          .catch((err) => {
            this.$message({
              message: err,
              type: "info",
            });
          });
      } else {
        this.$message({
          message: "请先选择文件再上传",
          type: "warning",
        });
      }
    },

    cancelUp() {
      this.file = "";
      this.fileName = "";
      this.uploadfile = "none";
      document.getElementsByClassName("addfile")[0].value = "";
    },
    // 导入文件结束=============
    backToIndex() {
      if (this.addOrEdit == "编辑") {
        let data = {
          name: this.name,
          phoneNumber: this.phoneNumber,
          otherContact: this.otherContact,
          remark: this.remark,
        };
        let equal = _.isEqual(data, JSON.parse(this.compare));

        if (equal) {
          this.close();
        } else {
          this.$confirm("数据信息有变化是否保存再离开？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            // type: "warning",
          })
            .then(() => {
              this.sureAdd();
            })
            .catch(() => {
              this.close();
            });
        }
      } else if (this.addOrEdit == "新增") {
        this.close();
      }
    },
    clickEdit(a) {
      this.addOrEdit = "编辑";
      this.tableData.forEach((item) => {
        if (item.id == a) {
          this.id = item.id;
          this.name = item.name;
          this.phoneNumber = item.phoneNumber;
          this.otherContact = item.otherContact;
          this.remark = item.remark;
          this.compare = JSON.stringify({
            name: item.name,
            phoneNumber: item.phoneNumber,
            otherContact: item.otherContact,
            remark: item.remark,
          });
        }
        this.show = "block";
      });
    },

    // 删除数据
    deleteOne(a) {
      // let that = this;
      this.$alert("确定删除这条信息？", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            service({
              method: "delete",
              url: `/address-book/${a}`,
            }).then((r) => {
              if (r.status == "SUCCESS") {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                if (this.currentNum == 1 && this.page > 1) {
                  this.page--;
                }
                this.clearCanShu();
                this.getRenderList();
                this.show = "none";
              }
            });
          } else {
            this.$message({
              type: "info",
              message: "取消删除",
            });
          }
        },
      });
    },
    // 弹窗确认按钮
    sureAdd() {
      this.data.id = this.id;
      this.data.name = this.name;
      this.data.phoneNumber = this.phoneNumber;
      this.data.remark = this.remark;
      this.data.otherContact = this.otherContact;
      if (this.addOrEdit == "编辑") {
        service({
          method: "put",
          data: this.data,
          url: "/address-book",
        })
          .then((r) => {
            if (r.status == "SUCCESS") {
              this.show = "none";
              this.$message({ message: "修改成功", type: "success" });
              this.getRenderList();
              this.clearCanShu();
            }
          })
          .catch((err) => {
            this.$message({
              type: "info",
              message: "出错了！",
            });
          });
      } else {
        service({
          method: "post",
          data: this.data,
          url: "/address-book",
        })
          .then((r) => {
            if (r.status == "SUCCESS") {
              this.$message({ message: "新增成功！", type: "success" });
              this.getRenderList();
              this.clearCanShu();
              this.show = "none";
            }
          })
          .catch((err) => {
            this.$message({
              type: "info",
              message: "出错了！",
            });
          });
      }
    },

    // 关闭弹窗
    close() {
      this.show = "none";
      this.show1 = "none";
      this.uploadfile = "none";
      this.clearCanShu();
    },
    // 新增
    addOne() {
      this.addOrEdit = "新增";
      this.show = "block";
    },
    // 导出文件
    getFileName() {
      let date = new Date();
      let year = date.getFullYear().toString();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day =
        date.getDate() > 10 ? date.getDate().toString() : "0" + date.getDate();
      let hour =
        date.getHours() > 10
          ? date.getHours().toString()
          : "0" + date.getHours();
      let min =
        date.getMinutes() > 10
          ? date.getMinutes().toString()
          : "0" + date.getMinutes();

      date = null;
      return `${year}${month}${day}${hour}${min}`;
    },
    async getExcelFile() {
      let that = this;
      let time = this.getFileName();

      this.token = sessionStorage.getItem("token");
      this.token = JSON.parse(this.token);
      axios({
        method: "get",
        url: this.$loadFile + "/address-book/export",
        responseType: "blob", // 关键：设置响应类型为blob
        data: {
          fileName: "装载作业",
        },
        headers: {
          token: that.token,
        },
      })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          // 创建一个隐藏的<a>标签，并设置其href属性为上面创建的URL
          const link = document.createElement("a");
          link.href = url;

          link.download = "船用通讯录-" + time + ".xls"; // 替

          document.body.appendChild(link);

          link.click();

          document.body.removeChild(link);

          window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          this.$message({
            message: "文件下载失败",
            type: "info",
          });
        });
    },

    sendMessage() {
      let res = rename();
      EventBus.emit("custom-event", res);
    },

    // 获取列表数据
    async getRenderList() {
      let data = {
        page: this.page,
        size: this.size,
      };

      await service({
        methods: "get",
        url: "/address-book/find-one-page",
        params: data,
      })
        .then((e) => {
          this.totalNumber = e.data.totalElements;
          this.totalPages = e.data.totalPages;
          if (this.totalPages == 0) {
            this.totalPages = 1;
          }

          if (this.page < this.totalPages) {
            this.color1 = "#268FDE";
          } else {
            this.color1 = "#EBEBEB";
          }
          if (this.page == 1) {
            this.color = "#EBEBEB";
          } else {
            this.color = "#268FDE";
          }
          this.tableData = e.data.content;
          this.currentNum = e.data.numberOfElements;
        })
        .catch((err) => {});
    },

    clearCanShu() {
      this.id = "";
      this.name = "";
      this.phoneNumber = "";
      this.remark = "";
      this.otherContact = "";
      this.data = {
        id: "",
        name: "",
        phoneNumber: "",
        remark: "",
        otherContact: "",
      };
    },

    clickLastPage() {
      if (this.page > 1) {
        this.page--;
        if (this.page == 1) {
          this.color = "#EBEBEB";
        } else {
          this.color = "#268FDE";
        }
        if (this.page < this.totalPages) {
          this.color1 = "#268FDE";
        }
        this.getRenderList();
      } else {
        this.color = "#EBEBEB";
      }
    },
    clickNextPage() {
      if (this.page < this.totalPages) {
        this.page++;
        this.color = "#268FDE";
        if (this.page == this.totalPages) {
          this.color1 = "#EBEBEB";
        } else {
          this.color1 = "#268FDE";
        }
      }
      this.getRenderList();
    },
    handSize() {
      if (window.innerWidth > 630) {
        if (this.$store.state.width == 200) {
          this.tableWidth = (window.innerWidth - 170) * 0.985 - 20 + "px";
        } else if (this.$store.state.width == 90) {
          this.tableWidth = (window.innerWidth - 60) * 0.985 - 20 + "px";
        }

        // this.changeLeft = "child1";
      } else {
        this.tableWidth = window.innerWidth - 30 + "px";
      }
    },
  },
  watch: {
    "$store.state.width"(newVal, oldVal) {
      //对数据执行操作

      if (window.innerWidth > 630) {
        if (newVal == 90) {
          this.tableWidth = (window.innerWidth - 60) * 0.985 - 20 + "px";
        } else if (newVal == 200) {
          this.tableWidth = (window.innerWidth - 170) * 0.985 - 20 + "px";
        }
      }
    },
    $route(to, from) {
      // 在这里根据参数的变化执行刷新页面的逻辑
      if (to.name == from.name) {
        this.close();
      }
    },
  },

  created() {
    this.sendMessage();
    this.getRenderList();
  },
  beforeMount() {
    if (window.innerWidth > 630) {
      if (this.$store.state.width == 200) {
        this.tableWidth = (window.innerWidth - 170) * 0.985 - 20 + "px";
      } else if (this.$store.state.width == 90) {
        this.tableWidth = (window.innerWidth - 60) * 0.985 - 20 + "px";
      }
    } else {
      this.tableWidth = window.innerWidth - 30 + "px";
    }
  },
  mounted() {
    let that = this;
    this.getRenderList();
    // this.sendMessage();
    window.addEventListener("resize", this.handSize);
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.handSize);
  },
};
</script>
<style lang="less" scoped>
.manyInput {
  width: 780px;
  height: 80vh;
  overflow: auto;
  // background: red;
  margin: auto;

  // overflow: scroll;
  .iuptInnerContain {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .inputInner {
      width: 375px;
      min-height: 35px;
      // background: blue;
      margin-right: 10px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      // justify-content: space-between;
      color: #365488;
      .name {
        width: 150px;
        height: 100%;
        line-height: 4vh;
        text-align: right;
        font-size: 15px;
      }
      .name1 {
        width: 210px;
        margin-left: 10px;
        height: 3vh;
        line-height: 3vh;
        text-indent: 1em;
        outline: none;
        font-size: 15px;
        border: none;
        // background: #ebebeb;
        color: #365488;
      }
      .inputContainer {
        width: 210px;
        margin-left: 5px;
      }
      .el-input__inner {
        background: white !important;
      }
      input {
        width: 220px;
        height: 34px;
        margin-left: 5px;
        border-radius: 5px;
        text-indent: 1em;
        outline: none;
        border: none;
        background: white !important;
        color: #365488;
        border: 1px solid #dcdfe6;
      }
      input::-webkit-input-placeholder {
        color: #a8abb2;
      }
      input[type="date"] {
        // padding: 5px;
        color: #365488;
        text-align: left;
        // border: 1px solid #365488;
        border-radius: 4px;
        // background-color: #fff;
        box-sizing: border-box; /* 确保内边距和边框不会影响元素的总宽度 */
      }
    }
    .el-date-picker .el-picker-panel {
      background-color: white !important; /* 你想要的背景颜色 */
    }
  }
}
.dialogText {
  margin: auto;
  width: 50%;
  line-height: 4vh;
  font-size: 25px;
  color: black;
  // text-indent: 10px;
  text-align: center;
  // font-size: 20px;
  font-weight: 800;
}

.dialog,
.dialog1 {
  width: 100%;
  height: 100%;
  background: #dfe6e8;
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  z-index: 100;
}

.loadHomeWork {
  overflow: hidden;
  width: 100%;
  height: 100%;
  position: relative;
  .loadHomeWorkIneer {
    width: 98.5%;
    height: 91vh;
    margin: auto;
    margin-top: 1vh;
    background: white;
    .loadTop {
      width: 50%;
      line-height: 4vh;
      font-size: 20px;
      color: #777676;
      // text-indent: 10px;
      margin-left: 10px;

      font-weight: 800;
    }
    .loadAndSearch {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;

      .search1 {
        display: flex;
        align-items: center;
        justify-content: center;
        // margin-top: 10px;
        margin-right: 10px;

        .searchButton {
          width: 64px;
          margin-top: -2px;
          background: #0470c1;
          font-size: 15px;
          height: 23px;
          text-align: center;
          line-height: 23px;
          // color: #777676;
        }
      }
    }
  }
}

.table {
  margin: auto;
  // margin-top: 2vh;
  height: 65vh;
  // background: red;
}

@media (min-width: 0px) and (max-width: 960px) {
  .manyInput {
    width: 375px !important;
    display: block !important;
    .inputInner {
      margin: auto !important;
      margin-top: 10px !important;
    }
  }
  .closeAndSrue {
    width: 150px;
  }
}
</style>
